<template>
  <div class="mHeader">
    <div class="w clearfix">
      <div class="top">
        <div class="title fl" @click="$router.push({name: 'home'})">通讯录</div>
        <div class="selection fr s-screen">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              <i :class="isLoginM ? 'el-icon-user-solid' : 'el-icon-user'" @click="drawer = true"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="openLogin" v-show="!isLoginM">登录</el-dropdown-item>
              <el-dropdown-item @click.native="$router.push({name: 'home'})" v-show="isLoginM && isHome" style="text-align:center;">主页</el-dropdown-item>
              <el-dropdown-item @click.native="$router.push({name: 'personal'})" v-show="isLoginM && personalShow">个人中心</el-dropdown-item>
              <el-dropdown-item @click.native="$router.push({name: 'admin'})" v-show="isAdminM && adminShow">管理员工</el-dropdown-item>
              <el-dropdown-item @click.native="$router.push({name: 'seat'})" v-show="isAdminM && seatShow">管理座位</el-dropdown-item>
              <el-dropdown-item @click.native="$router.push({name: 'bmks'})" v-show="isAdminM && bmksShow">管理部门</el-dropdown-item>
              <el-dropdown-item @click.native="outLogin" v-show="isLoginM" style="color: red;text-align:center;">退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <!-- 登录 -->
      <el-dialog :visible.sync="dialog.login" width="70%" :close-on-press-escape="false" :show-close="false">
        <template slot="title">
          <h5 class="dialog-title">登&nbsp;&nbsp;&nbsp;&nbsp;录</h5>
        </template>
        <el-form :model="loginInfo" ref="login" :rules="rules">

          <el-form-item label="手机号" prop="username">
            <el-input style="" placeholder="请输入手机号" v-model="loginInfo.username">
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-show="!loginActive">
            <el-input style="" placeholder="请输入密码" v-model="loginInfo.password" @keyup.enter.native="goLogin" type="password">
            </el-input>
          </el-form-item>
          <el-form-item label="验证码" prop="validcode" v-show="loginActive">
            <el-input placeholder="请输入验证码" v-model="loginInfo.validcode" style="width:116px;">
            </el-input>
            <el-button class="code-btn" type="primary" style="height:39px;float:right;max-width:94px;" @click="sendCode" :disabled="isSend">{{codeText}}</el-button>
          </el-form-item>
          <div class="btns">
            <el-button type="primary" @click="goLogin">登录</el-button>
            <!-- <el-button @click="dialog.login = false">取消</el-button> -->
          </div>
          <el-link class="fr" type="primary" @click="changeTabs(1)" v-show="!loginActive">短信验证登录</el-link>
          <el-link class="fr" type="primary" @click="changeTabs(0)" v-show="loginActive">密码登录</el-link>

        </el-form>

      </el-dialog>

    </div>
  </div>
</template>

<script>
export default {
  name: "mHeader",
  inject: ['reload'],
  data() {
    return {
      drawer: false,
      isLoginM: false,
      isClick: false,
      isAdminM: false,
      authorizeCode: '',// 权限码
      loginActive: 0,
      loginInfo: {
        username: "",
        password: "",
        validcode: "",
      },
      rules: {
        username: [{ validator: this.validPhone, trigger: "blur" }],
        password: [{ validator: this.validPassword, trigger: "blur" }],
        validcode: [{ validator: this.validateCode, trigger: "blur" }],
      },
      dialog: {
        login: false,
      },
      codeText: '获取验证码',
      isSend: false,
    };
  },
  created() {
    // this.init();
    this.getUserInfo();
    if (!this.isLoginM) {
      if (this._isMobile()) {
        this.openLogin();
      }
      this.checkCode();
      return
    }
  },
  computed: {
    isHome() {
      if (this.$route.name == 'personal' || this.$route.name == 'admin' || this.$route.name == 'admin' || this.$route.name == 'seat' || this.$route.name == 'bmks') {
        return true;
      } else {
        return false;
      }
    },
    personalShow() {
      if (this.authorizeCode != 101 && (this.$route.name != 'personal')) {
        return true;
      } else {
        return false;
      }
    },
    adminShow() {
      if (this.$route.name == 'admin') {
        return false;
      } else {
        return true;
      }
    },
    seatShow() {
      if (this.$route.name == 'seat') {
        return false;
      } else {
        return true;
      }
    },
    bmksShow() {
      if (this.$route.name != 'bmks') {
        return true;
      } else {
        return false;
      }
    },
  },
  methods: {
    init() {
    },
    // 获取用户数据
    getUserInfo() {
      let tokenString = this.$cookies.get("__tk");
      this.authorizeCode = this.$cookies.get("__ac");
      if (!tokenString) {
        this.isLoginM = false;
        this.clear();
      } else {
        this.isLoginM = true;
      }
      if (this.authorizeCode == 101 || this.authorizeCode == 301 || this.authorizeCode == 201) {
        this.isAdminM = true;
      } else {
        this.isAdminM = false;
      }

    },
    // 切换登录选项
    changeTabs(i) {
      if (this.loginActive == i) {
        return
      }
      if (this.$refs.login) {
        this.$refs.login.resetFields();
      }
      this.loginActive = i;
    },
    // 登录
    openLogin() {
      if (this.$refs.login) {
        this.$refs.login.resetFields();
      }
      this.dialog.login = true;
    },
    // 验证手机
    validPhone(rule, value, callback) {
      if (value === "") {
        // callback();
        callback(new Error("请输入手机号"));
      } else {
        if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
          callback(new Error("手机格式错误!"));
        } else {
          callback();
        }
      }
    },
    // 验证密码
    validPassword(rule, value, callback) {
      if (this.loginActive == 0) {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 验证码验证
    validateCode(rule, value, callback) {
      if (this.loginActive == 1) {
        if (value === "") {
          callback(new Error("请输入验证码"));
        } else if (!/\d{6}/.test(value)) {
          callback(new Error("验证码错误!"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 检查获取验证码是否倒计时
    checkCode() {
      if (this.$cookies.isKey('total')) {
        this.codeText = `重新发送(5s)`;// 倒计时显示
        this.isSend = true;

        let timer = setInterval(() => {
          let time = new Date().getTime();// 获取当前时间
          let date = this.$cookies.get('total') || 0;// 获取验证码有效时间
          if (parseInt((date - time) / 1000) <= 0) {// 判断有效时间是否结束
            clearInterval(timer);
            this.$cookies.remove('total')
            this.codeText = '获取验证码';
            this.isSend = false;
          } else {
            this.codeText = `重新发送(${parseInt((date - time) / 1000)}s)`;
          }
        }, 1000)
      }
    },
    //获取验证码
    sendCode() {
      //验证手机格式是否正确
      let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!reg.test(this.loginInfo.username)) {
        this.$message.warning("请输入正确的手机号！")
        return;
      }
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: '发送中...',
      });
      //发起获取验证码请求
      this.axios({
        method: 'POST',
        url: '/api/login/',
        data: this.$qs.stringify({
          username: this.loginInfo.username
        })
      }).then(res => {
        // console.log('res ==> ', res);
        if (res.data.data.status == 200) {
          this.$toast.success('验证码已发送');

          let date = new Date();// 获取验证码的时间
          date.setSeconds(date.getSeconds() + 61)// 加上倒计时的秒数
          this.$cookies.set('total', date.getTime(), 61)// 存入cookies
          this.codeText = `重新发送(60s)`;// 倒计时显示
          this.isSend = true;// 禁用按钮

          let timer = setInterval(() => {
            let time = new Date().getTime();// 获取当前时间
            date = this.$cookies.get('total') || 0;// 获取验证码有效时间
            if (parseInt((date - time) / 1000) <= 0) {// 判断有效时间是否结束
              clearInterval(timer);
              this.$cookies.remove('total')
              this.codeText = '获取验证码';
              this.isSend = false;
            } else {
              this.codeText = `重新发送(${parseInt((date - time) / 1000)}s)`;
            }
          }, 1000)
        } else {
          // this.$toast.clear();
          this.$toast.fail('验证码发送失败');
        }
      }).catch(err => {
        Toast.clear();
        this.$toast.fail("出现错误，请稍后再试");
      })
    },
    // 登录请求
    goLogin() {
      if (this.isClick) {
        return
      }
      this.isClick = true;
      this.$refs.login.validate(valid => {
        if (valid) {
          let data = {};
          if (this.loginActive == 0) {
            data = {
              username: this.loginInfo.username,
              password: this.loginInfo.password
            }
          } else {
            data = {
              username: this.loginInfo.username,
              text: this.loginInfo.validcode
            }
          }
          // 登录请求
          this.axios({
            method: 'POST',
            url: '/api/login/',
            data: this.$qs.stringify(data),
          }).then(res => {
            // console.log('res==>', res)
            if (res.data.data.status == 200) {
              this.$cookies.set('__tk', res.data.data.token);
              this.$cookies.set('__ac', res.data.data.authcode);
              this.$cookies.set('__un', this.loginInfo.username);
              this.dataRefreh();
              this.$toast.success(res.data.data.msg);
              this.dialog.login = false;
              this.getUserInfo();
              this.reload();
            } else {
              this.$toast(res.data.data.msg);
            }
            setTimeout(() => {
              this.isClick = false;
            }, 1000);
          }).catch(error => {
            this.$toast.fail(res.data.data.msg);
            setTimeout(() => {
              this.isClick = false;
            }, 1000);
          })

        } else {
          setTimeout(() => {
            this.isClick = false;
          }, 1000);
          this.$toast.fail('请填写正确的登录信息');
          return false;
        }
      });
    },
    // 退出
    outLogin() {
      if (this.isLoginM) {
        this.$cookies.keys().map((cookieName) => {
          this.$cookies.remove(cookieName);
        });
        this.authorizeCode = '';
        this.isLoginM = false;
        this.isAdminM = false;
        this.$toast('退出成功');
        this.clear();
        this.$router.push({ name: 'home' });
        this.openLogin();
      } else {
        return
      }
    },
    // 定时器
    dataRefreh() {
      // 计时器为空，操作
      window.time = setTimeout(() => {
        // console.log("刷新token");
        this.$cookies.keys().map((cookieName) => {
          this.$cookies.remove(cookieName);
        });
        this.getUserInfo();
      }, 1000 * 60 * 60 * 2);
    },
    // 停止定时器
    clear() {
      clearInterval(window.time); //清除计时器
      this.$router.push('/home')
    },
    // 是否为移动端
    _isMobile() {
      let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
      return flag;
    },
  },
};
</script>

<style lang="scss" scoped>
.mHeader {
  width: 100%;
  background-color: #fff;
  .top {
    height: 50px;
    line-height: 50px;
    font-size: 20px;
    .title {
      color: #0d2d84;
      padding-left: 20px;
      cursor: pointer;
    }
  }
  .selection {
    padding-right: 20px;
    color: #000;
    i {
      font-size: 25px;
    }
  }
  >>> .el-dialog {
    border-radius: 6px;
    .el-dialog__header {
      // padding: 0;
      text-align: center;
      height: 16px;
      line-height: 16px;
      padding-bottom: 0;
      .dialog-title {
        color: #0d2d84;
        font-size: 18px;
      }
    }
    .el-dialog__body {
      padding-top: 0px;
      .el-form {
        .el-form-item {
          margin-bottom: 15px;
          .el-form-item__label {
            float: none;
          }
        }
        .el-input {
          width: 100%;
        }
        .code-btn {
          padding-left: 5px;
          padding-right: 5px;
        }
      }
      .btns {
        text-align: center;
        height: 40px;
        line-height: 40px;
        margin-bottom: 14px;
        .el-button {
          // width: 99px;
          width: 212px;
        }
      }
      .el-link--inner {
        height: 14px;
        line-height: 1;
      }
    }
  }
}
</style>
